/**
 * 质控病种列表初始化
 */
var SdsTestPatient = {
    id: "entityTree",	//表格id
    seItem: null,		//选中的条目
    table: null,
    ztree: null,
    layerIndex: -1,
    entityId: 0
};

SdsTestPatient.onClickEntity = function (e, treeId, treeNode) {
    if (treeNode.pId == null || treeNode.pId == 0) {
        Sys.info("不能选择根节点（"+treeNode.name+"），请重新选择具体病种。");
        return false;
    }
    SdsTestPatient.entityId = treeNode.id;
    //查询质控项目
    SdsTestPatientTable.clearData();
    SdsTestPatientTable.search();
};

/**
 * 病种筛查配置管理初始化
 */
var SdsTestPatientTable = {
    id: "SdsTestPatientTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
SdsTestPatientTable.initColumn = function () {
    return [
        {
            width: 30, align: "center", valign: 'middle', sortable: true, formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize = $('#SdsTestPatientTable').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber = $('#SdsTestPatientTable').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {field: 'selectItem', checkbox: true},
        /*{title: '单病种', field: 'entityId', width:200, align: 'center', valign: 'middle'},*/
        {title: '病案号', field: 'mrNum', width: 100, align: 'center', valign: 'middle'},
        {title: '患者姓名', field: 'name', width: 120, align: 'center', valign: 'middle'},
        {title: '科室', field: 'admLocDesc', width: 120, align: 'center', valign: 'middle'},
        {title: '主管医师', field: 'admDoctorName', width: 120, align: 'center', valign: 'middle'},
        {
            title: '迟报天数',
            field: 'dishDate',
            width: 80,
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
                value = diffTimeWithNow(value);
                if (3 <= value && value < 5) {
                    return "<div style='background-color:#f0ad4e;'>" + value + "</div>";
                } else if (5 <= value && value < 7) {
                    return "<div style='background-color:#d9534f;'>" + value + "</div>";
                } else if (7 <= value) {
                    return "<div style='background-color:#9f4ef0;'>" + value + "</div>";
                } else {
                    return value;
                }
            }
        },
        {title: '入院日期', field: 'admDate', width: 120, align: 'center', valign: 'middle'},
        {title: '出院日期', field: 'dishDate', width: 120, align: 'center', valign: 'middle'},
        {title: '入单日期', field: 'inDate', width: 120, align: 'center', valign: 'middle'},
        {
            title: '操作',
            field: 'id',
            align: 'center',
            width: '120px',
            valign: 'middle',
            formatter: function (value, row, index) {
                // var _html = '<a href="javascript:SdsTestPatientTable.edit(\'' + row.id + '\')" title="填报"><i class="hisui-icon icon-write-order"></i></a>';
                var _html = '<a href="javascript:SdsTestPatientTable.upload(\'' + row.id + '\')" title="上报"><i class="hisui-icon icon-upload-cloud"></i></a>';
                _html += '<a href="javascript:SdsTestPatientTable.del(\'' + row.id + '\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
                _html += '<a href="javascript:SdsTestPatientTable.record(\'' + row.id + '\',\'' + row.mrNum + '\',\'' + row.name + '\')" title="日志"><i class="hisui-icon icon-clock-record"></i></a>';
                return _html;
            }
        }];
};

/**
 * 选中规则行填充上方控件
 */
SdsTestPatientTable.fillData = function (obj,$ele,field) {
    if ($($ele)[0].className == 'info') {
        SdsTestPatientTable.clearData();
        $($ele).removeClass('info');
    } else {
        SdsTestPatientTable.seItem = obj;
        $('#ruleType').combobox('setValue', obj.ruleType);
        $('#ruleDesc').val(obj.ruleDesc);
        $('#linkDept').combobox('setValues', obj.linkDept.split("#"));//多选
        $('#expressId').combobox('setValue', obj.expressId);
        $('#param').val(obj.param);
        $('#param2').val(obj.param2);
        $('#isActive').checkbox('setValue', obj.isActive == 1 ? true : false);
        // 改变选中行背景色
        $('#SdsTestPatientTableTable .info').removeClass('info');//移除class
        $($ele).addClass('info');//添加class
    }
}

/**
 * 清除上方控件数据
 */
SdsTestPatientTable.clearData = function ( ) {
    SdsTestPatientTable.seItem = null;
    $('#ruleType').combobox('clear');
    $('#ruleDesc').val('');
    $('#linkDept').combobox('clear');
    $('#expressId').combobox('clear');
    $('#param').val('');
    $('#param2').val('');
    $('#isActive').checkbox('clear');
    // 改变选中行背景色
    $('#SdsTestPatientTableTable .info').removeClass('info');//移除class
}

/**
 * 检查是否选中病种
 */
SdsTestPatientTable.check = function () {
    if (SdsTestPatient.entityId) {
        return true;
    } else {
        Sys.info("请先选中某一病种！");
        return false;
    }
};

/**
 * 打开查看病种入组病例详情
 */
SdsTestPatientTable.edit = function (id) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = Sys.open_c('病种入组病例详情', '/sds/sdsqcformshow?mrListId=' + id + '&checkPerm=1', null, function (){
            SdsTestPatientTable.table.refresh();
            SdsTestPatientTable.entityTestCnt();
        });
        this.layerIndex = index;
    }
};

/**
 * 删除病种入组病例
 */
SdsTestPatientTable.del = function (id) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        name = this.seItem.name
        flag = true;
    }
    if (flag) {
        var operation = function () {
            var ajax = new $ax(Sys.backendPath + "/sds/sdsqcincase/delete", function (data) {
                Sys.success("删除成功!");
                SdsTestPatientTable.table.refresh();
            }, function (data) {
                Sys.error("删除失败!" + data.responseJSON.message + "!");
            });
            params.mrListId = id;
            ajax.setData(params);
            ajax.start();
        };
        Sys.confirm("是否删除病种入组病例?", operation);
    }
};

/**
 * 单病种上报
 */
SdsTestPatientTable.upload = function (id) {
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var ajax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/upload/" + id, function (UpRet) {
        $.messager.progress("close")
        if (UpRet.code == 1) {
            $.messager.popover({msg: '上传成功！', type: 'success', timeout: 1000})
            //更新状态
            var ax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '状态更新成功！', type: 'success', timeout: 1000})
                SdsTestPatientTable.search();
            }, function (data) {
                $.messager.alert("错误提示", "状态更新错误!", 'info');
            });
            // 如果返回信息Code为“1”，且无message信息，则说明前置机该病种为测试状态，将该入组记录加个测试上报标识
            if (UpRet.message == null || UpRet.message == "") {
                ax.set('testFlg', 1);
            }
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.start();
        } else if (UpRet.message.indexOf('重复') > -1) {
            //更新状态
            var ax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '已存在上传记录，状态更新成功！', type: 'success', timeout: 1000})
                SdsTestPatientTable.search();
            }, function (data) {
                $.messager.alert("错误提示", "已存在上传记录，状态更新错误!", 'info');
            });
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.set('reason', '');
            ax.set('resume', '');
            ax.start();
        } else {
            $.messager.alert("错误提示", "表单上传失败!Error=" + UpRet.message, 'info');
        }
    }, function (data) {
        $.messager.alert("错误提示", "表单上传失败!", 'info');
    });
    ajax.setAsync();
    ajax.start();
}

$("#btnBatchUp").on('click', function () {
    var selectRows = $("#SdsTestPatientTable").bootstrapTable('getSelections');
    if (selectRows.length == 0) {
        Sys.error("请选择要上报的病例！");
        return;
    }
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var message = "";
    var successCnt = 0;
    var errorCnt = 0;
    for (var i = 0, l = selectRows.length; i < l; i++) {
        var row = selectRows[i];
        var id = row.id;
        var mrNo = row.mrNum;
        var name = row.name;
        var ajax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/upload/" + id, function (UpRet) {
            if (UpRet.code == 1) {
                //更新状态
                var ax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/changeMrStatus", function (data) {
                });
                // 如果返回信息Code为“1”，且无message信息，则说明前置机该病种为测试状态，将该入组记录加个测试上报标识
                if (UpRet.message == null || UpRet.message == "") {
                    ax.set('testFlg', 1);
                }
                ax.set('mrListId', id);
                ax.set('status', 'Up');
                ax.start();
                successCnt++;
            } else if (UpRet.message.indexOf('重复') > -1) {
                //更新状态
                var ax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/changeMrStatus", function (data) {
                });
                ax.set('mrListId', id);
                ax.set('status', 'Up');
                ax.set('reason', '');
                ax.set('resume', '');
                ax.start();
                successCnt++;
            } else {
                message += name + "(" + mrNo + ")：" + UpRet.message + "<br>";
                errorCnt++;
            }
        }, function (UpRet) {
            message += name + "(" + mrNo + ")：表单上传失败!" ;
            errorCnt++;
        });
        ajax.start();
    }
    $.messager.progress("close");

    $.messager.alert("上报结果", "成功例数："+ successCnt + " " + "错误例数：" + errorCnt + "<hr>" + message, 'info');

    SdsTestPatientTable.table.refresh();
    SdsTestPatientTable.entityTestCnt();
});

/**
 * 打开查看病例操作记录
 */
SdsTestPatientTable.record = function (id, mrno, name) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = Sys.open('【填报审核操作日志】姓名：' + name + ' 病案号：' + mrno, Sys.backendPath + '/sds/sdsqcincaseoperlog/' + id, ['800px', '420px']);
        this.layerIndex = index;
    }
};

SdsTestPatientTable.qcFormShow = function (r, e, f) {
    var index = Sys.open_c('病种入组病例详情', '/sds/sdsqcformshow?mrListId=' + r.id + '&checkPerm=1',null, function (){
        SdsTestPatientTable.table.refresh();
        SdsTestPatientTable.entityTestCnt();
    } );
    this.layerIndex = index;
}

/**
 * 查询
 */
SdsTestPatientTable.search = function () {
    var queryData = {};
    queryData['entityId'] = SdsTestPatient.entityId;
    SdsTestPatientTable.table.refresh({query: queryData});
};

SdsTestPatientTable.entityTestCnt = function () {
    // 有测试病例的病种进行标识
    var ajax = new $ax(Sys.backendPath + "/sds/common/entityTestGroup", function (data) {
        var treeObj = $.fn.zTree.getZTreeObj("entityTree");
        for (var i=0;i<data.length;i++){
            var entityTest = data[i];
            var entityId = entityTest["entityId"];
            var testCnt = entityTest["testCnt"];
            if (testCnt > 0) {
                var node = treeObj.getNodeByParam("id", entityId);
                $("#"+node.tId+"_span").css("color",'red');
            }
        }
    }, function (data) {
        Sys.error("渲染失败!" + data.responseJSON.message + "!");
    });
    ajax.start();
}

$(function () {
    //查询病种树
    var ztree = new $ZTree("entityTree", Sys.backendPath + "/sds/sdsqcentity/tree");
    ztree.bindOnClick(SdsTestPatient.onClickEntity);
    ztree.init();
    SdsTestPatient.ztree = ztree;
    fuzzySearch('entityTree','#seachKey',null,true);

    //项目规则获取
    var defaultColunms = SdsTestPatientTable.initColumn();
    var table = new BSTable(SdsTestPatientTable.id, Sys.backendPath + "/sds/common/testPatientList", defaultColunms);
    table.setPaginationType("server");
    table.setPageSize(10);
    table.setSubHeight(-40);
    table.setShowExport(false);
    table.setShowRefresh(false);
    table.setShowToggle(false);
    table.setShowColumns(false);
    // table.setOnDblClickRow(SdsTestPatientTable.qcFormShow); //双击数据行打开表单填报
    table.setQueryParams({"entityId":0});
    SdsTestPatientTable.table = table.init();

    SdsTestPatientTable.entityTestCnt();
});

/**
 * 计算与当前时间的时间差（天）
 */
function diffTimeWithNow(time) {
    if (time == "") {
        return "";
    }
    time = time.replace(/-/g, '/');
    var new_date = new Date(); //新建一个日期对象，默认现在的时间
    var old_date = new Date(time);
    var diff_time = (new_date - old_date) / 1000; //计算时间差,并把毫秒转换成秒
    var days = parseInt(diff_time / 86400);
    return days;
}